﻿using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using mojoPortal.Web;
using Resources;
using mojoPortal.Web.Framework;
using System.Collections;
using mojoPortal.Business;
using Telerik.Web.UI;
using System.Linq;
using ud_gSDMS.Code_Service;

namespace ud_gSDMS.timesheet
{
    public partial class Check_List : mojoBasePage
    {
        private int pageId = -1;
        private int moduleId = -1;
        protected string _pageId;
        private SiteUser siteUser;
        private int currentUserID = 0;

        void Page_Load(object sender, EventArgs e)
        {
            if (SiteUtils.GetCurrentSiteUser()==null)
            {
                WebUtils.SetupRedirect(this, SiteRoot + "/AccessDenied.aspx");
            }
            else
            {
                siteUser = SiteUtils.GetCurrentSiteUser();
                currentUserID = siteUser.UserId;
                _pageId = pageId.ToString();
                if (!Page.IsPostBack)
                {
                    PopulateLabels();
                    PopulateControls();
                }
            }
        }
        private void PopulateLabels()
        {

        }
        private void PopulateControls()
        {
            datTimeSheet_Date_from.SelectedDate = DateTime.Now.AddDays(-1);
            datTimeSheet_Date_to.SelectedDate = DateTime.Now;
            datTimeSheet_Date_from.MaxDate = DateTime.Now;
            datTimeSheet_Date_to.MaxDate = DateTime.Now;
            LoadControl();
            LoadGrid();
        }

        private void CreateGrid()
        {
            grdTimeSheet.Columns.Clear();
            
            //ItemTemplate STT
            TemplateField col = new TemplateField();

            col.HeaderText = "STT";
            col.ItemStyle.CssClass = "stt";
            col.ItemStyle.HorizontalAlign = HorizontalAlign.Center;

            ColumnTextTemplate temp = new ColumnTextTemplate();
            temp.eval = "STT";
            col.ItemTemplate = temp;
            grdTimeSheet.Columns.Add(col);

            //ItemTemplate Date
            col = new TemplateField();

            col.HeaderText = "Date";
            col.ItemStyle.CssClass = "txtdate";
            col.SortExpression = "Date";
            col.ItemStyle.HorizontalAlign = HorizontalAlign.Center;

            temp = new ColumnTextTemplate();
            temp.eval = "Date";
            col.ItemTemplate = temp;
            grdTimeSheet.Columns.Add(col);

            //ItemTemplate Project Code
            col = new TemplateField();
            col.HeaderText = "Project Code";
            col.ItemStyle.CssClass = "txtMember";
            col.SortExpression = "Project_Code";
            col.ItemStyle.HorizontalAlign = HorizontalAlign.Center;

            temp = new ColumnTextTemplate();
            temp.eval = "Project_Code";
            col.ItemTemplate = temp;
            grdTimeSheet.Columns.Add(col);

            //ItemTemplate Project Leader
            col = new TemplateField();
            col.HeaderText = "Leader";
            col.ItemStyle.CssClass = "txtMember";
            col.SortExpression = "Leader";
            col.ItemStyle.HorizontalAlign = HorizontalAlign.Center;

            temp = new ColumnTextTemplate();
            temp.eval = "Leader";
            col.ItemTemplate = temp;
            grdTimeSheet.Columns.Add(col);

            ////ItemTemplate Engineers
            var engineers = gSDMS_BL.mp_UserRole_Search_RoleLst(0, 5 , 0);
            var engineersDist = (from c in engineers
                                 select c.mp_User.LoginName).Distinct();

            foreach (var engineer in engineersDist)
            {
                col = new TemplateField();

                col.HeaderText = engineer;
                col.ItemStyle.CssClass = "txtMember";
                col.SortExpression = engineer;
                col.ItemStyle.HorizontalAlign = HorizontalAlign.Center;

                temp = new ColumnTextTemplate();
                temp.eval = engineer;
                col.ItemTemplate = temp;
                grdTimeSheet.Columns.Add(col);
            }
        }

        private void LoadGrid()
        {
            //cboAccount.Text.Trim() == "" ? null : cboAccount.SelectedValue,
            var data = gSDMS_BL.ud_gSDMS_TIMESHEET_CheckList_Search(datTimeSheet_Date_from.SelectedDate == null ? null : datTimeSheet_Date_from.SelectedDate.Value.ToShortDateString(),
                                                         datTimeSheet_Date_to.SelectedDate == null ? null : datTimeSheet_Date_to.SelectedDate.Value.ToShortDateString(),
                                                         cboProjectCode.SelectedValue, cboProjectLeader.SelectedValue);

            
            if (ViewState["SortExpression"] != null)
            {
                var dv = data.DefaultView;
                dv.Sort = ViewState["SortExpression"].ToString();
                data = dv.Table;
            }
            CreateGrid();

            grdTimeSheet.DataSource = data;         
            grdTimeSheet.DataBind();

            for (int row = 0; row < grdTimeSheet.Rows.Count; row++)
            {
                DataRow dataRow = data.Rows[row];
                var usersInProject = gSDMS_BL.ud_gSDMS_PROJECT_Member_Get_Lst(dataRow["Project_ID"].ToString());
                var loginNames = from c in usersInProject
                                 select c.LoginName;

                for (int col = 4; col < grdTimeSheet.Columns.Count; col++)
                {
                    if (loginNames.Contains(grdTimeSheet.Columns[col].SortExpression))
                    {
                        if (row % 2 == 0)
                            grdTimeSheet.Rows[row].Cells[col].BackColor = System.Drawing.Color.GreenYellow;
                        else
                            grdTimeSheet.Rows[row].Cells[col].BackColor = System.Drawing.Color.PaleGreen;
                    }                 
                }
            }
            ViewState["listTimesheet"] = data;
        }

        private void LoadControl()
        {
            cboProjectCode.DataValueField = "Project_ID";
            cboProjectCode.DataTextField = "Code";
            cboProjectCode.DataSource = gSDMS_BL.ud_gSDMS_PROJECT_GetList();
            cboProjectCode.DataBind();
            cboProjectCode.Items.Insert(0, new RadComboBoxItem("", ""));
            cboProjectCode.SelectedValue = "";

            cboProjectLeader.DataValueField = "UserID";
            cboProjectLeader.DataTextField = "LoginName";
            cboProjectLeader.DataSource = gSDMS_BL.ud_gSDMS_PROJECT_Leader_Tab();
            cboProjectLeader.DataBind();
            cboProjectLeader.Items.Insert(0, new RadComboBoxItem("", ""));
            cboProjectLeader.SelectedValue = "";
        }
        //private void grdTimeSheet_SelectedIndexChanging(object sender, GridViewPageEventArgs e)
        //{

        //}

        private void grdTimeSheet_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grdTimeSheet.PageIndex = e.NewPageIndex;
            LoadGrid();
        }
        
        private void grdTimeSheet_RowCommand(object sender, GridViewCommandEventArgs e)
        {
        }
        void grdTimeSheet_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            LoadGrid();
        }
        void grdTimeSheet_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (ViewState["Direction"] == null) ViewState["Direction"] = " DESC";
            else if (ViewState["Direction"].ToString() == " ASC") ViewState["Direction"] = " DESC";
            else if (ViewState["Direction"].ToString() == " DESC") ViewState["Direction"] = " ASC";
            grdTimeSheet.EditIndex = -1;
            string strSortExp = e.SortExpression + ViewState["Direction"].ToString();
            ViewState["SortExpression"] = strSortExp;

            LoadGrid();
        }

        void btnSearch_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            LoadGrid();
        }

        void grdTimeSheet_RowDataBound(object sender, GridViewRowEventArgs e)
        {
        }

        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
            Load += Page_Load;
        }

        protected override void OnInit(EventArgs e)
        {
            LoadParams();
            LoadPanels();
            base.OnInit(e);
            grdTimeSheet.PageIndexChanging += grdTimeSheet_PageIndexChanging;
            grdTimeSheet.RowCommand += grdTimeSheet_RowCommand;
            grdTimeSheet.RowDeleting += grdTimeSheet_RowDeleting;
            grdTimeSheet.Sorting += grdTimeSheet_Sorting;
            grdTimeSheet.RowDataBound += grdTimeSheet_RowDataBound;
            btnSearch.Click += btnSearch_Click;
            //btnFinish.Click += btnFinish_Click;
            SuppressPageMenu();
        }

        //void btnFinish_Click(object sender, EventArgs e)
        //{
        //    WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl());
        //}

        private void LoadParams()
        {
            pageId = WebUtils.ParseInt32FromQueryString("pageid", pageId);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", true, moduleId);
        }

        private void LoadPanels()
        {
            Hashtable settings = ModuleSettings.GetModuleSettings(moduleId);
            //config = new ContactFormConfiguration(settings);
            bool showLeftColumnAdmin = ConfigHelper.GetBoolProperty("ShowLeftColumnAdmin", false);
            bool showRightColumnAdmin = ConfigHelper.GetBoolProperty("ShowRightColumnAdmin", false);
            bool showTopColumnAdmin = ConfigHelper.GetBoolProperty("ShowTopColumnAdmin", false);
            bool showBottomColumnAdmin = ConfigHelper.GetBoolProperty("ShowBottomColumnAdmin", false);
            int showCenterColumnAdmin = ConfigHelper.GetIntProperty("ShowCenterColumnAdmin", 0);
            LoadSideContent(showLeftColumnAdmin, showRightColumnAdmin, showTopColumnAdmin, showBottomColumnAdmin, showCenterColumnAdmin);
        }
        #endregion
    }

    public class ColumnTextTemplate : ITemplate
    {
        public string eval { set ;get;}

        
        // Instantiate the elements of the template in the given
        // container. In this case, a DataGridItem element.

        public void InstantiateIn(Control container)
        {
            Label lblLastName = new Label();
            lblLastName.DataBinding += new EventHandler(this.BindItem);
            container.Controls.Add(lblLastName);
        }

        private void BindItem(Object sender, EventArgs e)
        {
            Label l = (Label)sender;
            GridViewRow container = (GridViewRow)l.NamingContainer;
            l.Text = ((DataRowView)container.DataItem)
                [eval].ToString();
        }

    }
}